//
//  OrganizationViewController.m
//  ShangHaiTuJI
//
//  Created by xiaoxiangtuji on 2017/8/14.
//  Copyright © 2017年 xiaoxiangtuji. All rights reserved.
//

#import "OrganizationViewController.h"
#import "YYInfiniteLoopView.h"
#import "LearnSkillMiddleCell.h"
#import "ListenStoryHeaderCell.h"
#import "OrganationSeekCell.h"
#import "OrganationBottomCell.h"
#import "OrganationApplayINViewController.h"
#import "InstituteModel.h"
#import "CatagoryModel.h"
#import "InstitutionsDetailContainViewController.h"
#import "OrganationHeaderView.h"
#import "GBPopMenuButtonView.h"
#import "SearchResultViewController.h"
#import "DistanceView.h"
#import "ScreeningView.h"
#import "LocaltionChooseViewController.h"
#import "LHCityPickerController.h"
#import "EVNCustomSearchBar.h"
#import "InstituTypeChooseView.h"
#import "LoginUserViewController.h"
#import <MapKit/MapKit.h>
@interface OrganizationViewController ()<UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UICollectionViewDataSource,YYInfiniteLoopViewDelegate,GBMenuButtonDelegate,UIViewControllerTransitioningDelegate,EVNCustomSearchBarDelegate,UITabBarDelegate,UITabBarControllerDelegate>
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)UICollectionViewFlowLayout *flowLayout;
@property(nonatomic,strong)NSMutableArray *bottomDataArray;
@property(nonatomic,strong)NSMutableArray *middleDataArray;
@property(nonatomic,strong)UIButton *localBtn;
@property(nonatomic,strong)UIView *backView;
@property(nonatomic,strong)DistanceView *distanceView;
@property(nonatomic,strong)InstituTypeChooseView *screeView;
@property(nonatomic,assign)BOOL isSearch;
@property(nonatomic,strong)NSMutableArray *resultsArray;
@property(nonatomic,strong)NSMutableArray *chooseIdsArray;
@property(nonatomic,strong)NSMutableArray *distanceArray;
@property(nonatomic,strong)NSMutableArray *dsArray;
@property(nonatomic,strong)NSIndexPath *selectedIndexpath;
@property(nonatomic,strong)OrganationHeaderView *headerView;
@property(nonatomic,strong)UIButton *rightbtn;
@property(nonatomic,strong)UIButton *leftbtn;
//@property(nonatomic,assign)NSInteger currentPage;
/**
 * 导航搜索框EVNCustomSearchBar
 */
@property (strong, nonatomic) EVNCustomSearchBar *searchBar;
//@property(nonatomic,strong)InstituTypeChooseView *shareView;
@end

@implementation OrganizationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _isSearch = NO;
    [self createSuspensionBtn];
    [self createLocaltionBtn];
    [self initSearchBar];
    [self createCollectionUI];
    [self getMiddleAndBottomListDataWithTypeId];
//    [self getMiddleAndBottomListDataWithTypeId:@"" AndWithSort:@"0"];
//    [self addRefresh];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@""];
    NSLog(@"你猜");
    // Do any additional setup after loading the view.
}
#pragma mark -图片轮播
- (void)loopViewDelegateAndAddToFatherView:(UIView *)faterView{
    NSArray *array = @[@"20160904063832_17690.jpg",@"amZ24VI960Lu",@"banner.jpg"];
    // 类方法
    YYInfiniteLoopView *loopView = [YYInfiniteLoopView
                                    infiniteLoopViewWithImageUrls:array
                                    titles:nil
                                    didSelectedImage:^(NSInteger index) {
                                        NSLog(@"%zd",index);
                                    }];
    // 设置代理
    loopView.delegate = self;
    loopView.timeInterval = 5;
    loopView.currentPageIndicatorColor = [UIColor yellowColor];
    loopView.pagePosition = InfiniteLoopViewPagePositionCenter;
    loopView.frame = CGRectMake(0, 0, WIDTH, scaleTopAndBottom(175));
    [faterView addSubview:loopView];
}
#pragma mark - YYInfiniteLoopViewDelegate
- (void)infiniteLoopView:(YYInfiniteLoopView *)infiniteLoopView
        didSelectedImage:(NSInteger)selectedImageIndex {
    [self didSelectedImageWithIndex:selectedImageIndex];
}

- (void)didSelectedImageWithIndex:(NSInteger)index {
    NSLog(@"点击了%ld",index);
}
#pragma mark -创建collectionView
-(void)createCollectionUI{
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout.sectionHeadersPinToVisibleBounds = YES;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT - 64) collectionViewLayout:self.flowLayout];
    [self.view addSubview:self.collectionView];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"LearnAbilitysHeaderone"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"LLKcollectionFooter"];
    UINib *nib1 = [UINib nibWithNibName:@"ListenStoryHeaderCell" bundle:nil];
    [self.collectionView registerNib:nib1 forCellWithReuseIdentifier:@"ListenStoryHeaderCell"];
    [self.collectionView registerClass:[OrganationSeekCell class] forCellWithReuseIdentifier:@"OrganationSeekCell"];
    [self.collectionView registerClass:[OrganationBottomCell class] forCellWithReuseIdentifier:@"OrganationBottomCell"];
            [self createSuspensionBtn];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    if (_isSearch) {
        return 1;
    }
    return 2;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (_isSearch) {
        return self.bottomDataArray.count;
    }
    if (section == 1) {
      return self.bottomDataArray.count;
    }else{
        return 1;
    }
   
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (_isSearch) {
        OrganationBottomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"OrganationBottomCell" forIndexPath:indexPath];
        for (UIView *subView in cell.contentView.subviews) {
            [subView removeFromSuperview];
        }
        cell.model = self.resultsArray[indexPath.row];
        cell.detailbtn.tag = 1000 + indexPath.row;
        [cell.detailbtn addTarget:self action:@selector(GoInstitutionIntroduceAndDetail:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }else{
        if (indexPath.section == 0) {
            ListenStoryHeaderCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ListenStoryHeaderCell" forIndexPath:indexPath];
            [self loopViewDelegateAndAddToFatherView:cell.contentView];
            return cell;
        }else{
            OrganationBottomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"OrganationBottomCell" forIndexPath:indexPath];
            for (UIView *subView in cell.contentView.subviews) {
//                if ([subView isKindOfClass:[UILabel class]]) {
//                    [subView removeFromSuperview];
//                }
                [subView removeFromSuperview];
            }
            cell.model = self.bottomDataArray[indexPath.row];
//            if (self.distanceArray.count < self.bottomDataArray.count) {
//                NSString *distanceStr = [NSString stringWithFormat:@"%@",cell.collectbtn.titleLabel.text];
//                [self.distanceArray addObject:distanceStr];
//            }
//            NSLog(@"距离的值%@",self.distanceArray);
//            if (self.distanceArray.count == self.bottomDataArray.count) {
//                [cell.collectbtn setTitle:self.distanceArray[indexPath.row] forState:UIControlStateNormal];
//            }

            cell.detailbtn.tag = 1000 + indexPath.row;
            [cell.detailbtn addTarget:self action:@selector(GoInstitutionIntroduceAndDetail:) forControlEvents:UIControlEventTouchUpInside];
            return cell;
        }
    }
    
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (_isSearch) {
        return CGSizeMake(WIDTH, scaleTopAndBottom(100));
    }
    if (indexPath.section == 0) {
        return CGSizeMake(WIDTH, scaleTopAndBottom(175));
    }else{
        return CGSizeMake(WIDTH, scaleTopAndBottom(100));
    }
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    if (_isSearch) {
        return 1;
    }
    if (section == 0) {
        return 0;
    }
    return scaleTopAndBottom(1);
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    if (_isSearch) {
        return scaleLeftAndRight(1);
    }
    if (section == 0) {
        return 0;
    }
    return scaleLeftAndRight(1);
}
#pragma mark - 注册collectionView的头部视图
//collectionview的头部视图的设置
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (_isSearch) {
        return nil;
    }
    if ([kind isEqual:UICollectionElementKindSectionHeader]) {
        if (indexPath.section == 0) {
            return nil;
        }else{
            UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"LearnAbilitysHeaderone" forIndexPath:indexPath];
            [self createHeaderViewAboutUI:@"申请机构入驻" AndAddSubviewToFatherview:view];
            return view;
        }
    }else{
        if (indexPath.section == 1) {
            return nil;
        }else{
            UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"LLKcollectionFooter" forIndexPath:indexPath];
            view.backgroundColor = COLOR_HEX(0xE8E8E8);
//            for (UIView *subView in view.subviews) {
//                [subView removeFromSuperview];
//            }
//            [self createHeaderViewAboutUI:@"申请机构入驻" AndAddSubviewToFatherview:view];
            return view;
        }
    }
    
}
//设置头部视图的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (_isSearch) {
        return CGSizeMake(0.0f, 0.0f);
    }
    if (section == 0) {
        return CGSizeMake(0.f, 0.f);
    }
    return CGSizeMake(WIDTH, scaleTopAndBottom(220) + scaleTopAndBottom(40) + 2);
}
//设置尾视图
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    if (_isSearch) {
        return CGSizeZero;
    }
    if (section == 1 || section == 2) {
        return CGSizeZero;
    }
    return CGSizeMake(WIDTH, scaleTopAndBottom(5));
}

////设置头部视图的大小
//-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
//    return CGSizeZero;
//}
////设置尾视图
//-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
//    if (section == 0) {
//            return CGSizeMake(WIDTH, scaleTopAndBottom(220) + scaleTopAndBottom(40) + 2);
//    }else{
//        return CGSizeZero;
//    }
//
//}




//创建tableview的头部视图
-(UICollectionReusableView *)createHeaderViewAboutUI:(NSString *)headerTitle AndAddSubviewToFatherview:(UICollectionReusableView *)fatherView{
//    if (self.headerView) {
//        return nil;
//    }
//    if (self.headerView) {
//        return fatherView;
//    }
    self.headerView = [[OrganationHeaderView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, scaleTopAndBottom(210))];
    __weak typeof(self) weakSelf = self;
    weakSelf.headerView.typeChooseBlock = ^(NSString *insitiId,NSIndexPath *index) {
//        self.currentPage = 1;
        weakSelf.selectedIndexpath = index;
        [[NSUserDefaults standardUserDefaults] setObject:insitiId forKey:@"insitiId"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [weakSelf.bottomDataArray removeAllObjects];
        [weakSelf getMiddleAndBottomListDataWithTypeId:insitiId AndWithSort:@"0"];
    };
    [fatherView addSubview:self.headerView];
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, scaleTopAndBottom(210), WIDTH, 2)];
    lineView.backgroundColor = COLOR_HEX(0xE8E8E8);
    [fatherView addSubview:lineView];
    UIView *toplineView = [[UIView alloc] init];
    toplineView.backgroundColor = [UIColor lightGrayColor];
    [fatherView addSubview:toplineView];
    [toplineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(fatherView);
        make.top.equalTo(lineView.mas_bottom);
        make.height.mas_equalTo(1);
        make.centerX.equalTo(fatherView.mas_centerX);
    }];
    UIView *bottomlineView = [[UIView alloc] init];
    bottomlineView.backgroundColor = [UIColor lightGrayColor];
    [fatherView addSubview:bottomlineView];
    [bottomlineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(fatherView.mas_left).offset(scaleLeftAndRight(10));
        make.bottom.equalTo(fatherView.mas_bottom);
        make.height.mas_equalTo(1);
        make.centerX.equalTo(fatherView.mas_centerX);
    }];
    
    UIView *bgView = [[UIView alloc] init];
    bgView.backgroundColor = [UIColor whiteColor];
    [fatherView addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.equalTo(fatherView);
        make.top.equalTo(toplineView.mas_bottom);
        make.bottom.equalTo(bottomlineView.mas_top);
        make.centerX.equalTo(fatherView.mas_centerX);
    }];
    UIView *centerlineView = [[UIView alloc] init];
    [bgView addSubview:centerlineView];
    [centerlineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(bgView);
        make.size.mas_equalTo(CGSizeMake(1, scaleTopAndBottom(15)));
    }];
  
    self.leftbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _leftbtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [_leftbtn setTitle:@"距我最近 " forState:UIControlStateNormal];
    [_leftbtn setImage:[UIImage imageNamed:@"arrowdown89889"] forState:UIControlStateNormal];
//    [leftbtn setImage:[UIImage imageNamed:@"距我IOCN"] forState:UIControlStateSelected];
    [_leftbtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_leftbtn setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
    [_leftbtn addTarget:self action:@selector(showDistanceViewChoose:) forControlEvents:UIControlEventTouchUpInside];
    _leftbtn.tag = 100001;
    [bgView addSubview:_leftbtn];
//    leftbtn.backgroundColor = [UIColor redColor];
    [_leftbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(bgView);
        make.left.equalTo(bgView.mas_left).offset(30);
        make.right.equalTo(centerlineView.mas_left).offset(-30);
        make.top.equalTo(bgView.mas_top);
    }];
    CGFloat imageWidth = _leftbtn.imageView.bounds.size.width;
    CGFloat labelWidth = _leftbtn.titleLabel.bounds.size.width;
    _leftbtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
    _leftbtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth, 0, imageWidth);
    /*右边的页面*/
    self.rightbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _rightbtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [_rightbtn setTitle:@"筛选 " forState:UIControlStateNormal];
    [_rightbtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_rightbtn setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
    [_rightbtn setImage:[UIImage imageNamed:@"右上角筛选-3"] forState:UIControlStateNormal];
    [_rightbtn setImage:[UIImage imageNamed:@"右上角筛选-4"] forState:UIControlStateSelected];
    [_rightbtn addTarget:self action:@selector(showDistanceViewChoose:) forControlEvents:UIControlEventTouchUpInside];
    _rightbtn.tag = 100002;
    [bgView addSubview:_rightbtn];
    [_rightbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(bgView);
        make.right.equalTo(bgView.mas_right).offset(-30);
        make.left.equalTo(centerlineView.mas_right).offset(30);
        make.top.equalTo(bgView.mas_top);
    }];
    CGFloat imageWidth1 = _rightbtn.imageView.bounds.size.width;
    CGFloat labelWidth1 = _rightbtn.titleLabel.bounds.size.width;
    _rightbtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth1, 0, -labelWidth1);
    _rightbtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth1, 0, imageWidth1);
    centerlineView.backgroundColor = [UIColor lightGrayColor];
    return fatherView;
}


-(void)ApplyOrganationInput:(UIButton *)btn{
    OrganationApplayINViewController *inputVc = [[OrganationApplayINViewController alloc] init];
    [self.navigationController pushViewController:inputVc animated:YES];
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        InstituteModel *model;
        if (_isSearch) {
            model = self.resultsArray[indexPath.row];
        }else{
            model = self.bottomDataArray[indexPath.row];
        }
        InstitutionsDetailContainViewController *vc = [[InstitutionsDetailContainViewController alloc] init];
        vc.instituId = model.Id;
        vc.nameStr = model.name;
        vc.addressStr = [NSString stringWithFormat:@"%@%@%@%@",model.province,model.city,model.area,model.addresss];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    
}


-(NSMutableArray *)bottomDataArray{
    if (_bottomDataArray == nil) {
        _bottomDataArray = [[NSMutableArray alloc] init];
    }
    return _bottomDataArray;
}
-(NSMutableArray *)middleDataArray{
    if (_middleDataArray == nil) {
        _middleDataArray = [[NSMutableArray alloc] init];
    }
    return _middleDataArray;
}
/**
 获取机构列表
 */
-(void)getMiddleAndBottomListDataWithTypeId:(NSString *)typeId AndWithSort:(NSString *)sortId{
//    [self.bottomDataArray removeAllObjects];
    dispatch_queue_t gloabQue = dispatch_get_global_queue(0, 0);
    dispatch_async(gloabQue, ^{
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        NSString *url = ServerIp@"/institutionApp/institutionList";
        
        NSString *latitude = [[NSUserDefaults standardUserDefaults] objectForKey:@"latitude"];
        NSString *longtitude = [[NSUserDefaults standardUserDefaults] objectForKey:@"longtitude"];
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:sortId,@"sortord",latitude,@"institution_lat",longtitude,@"institution_lng",typeId,@"institutionCategory_id",@"50",@"showCount", nil];
        NSLog(@"参数的值%@",param);
        [manager POST:url parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSArray *listArra = jsonDic[@"list"];
            for (NSDictionary *dic in listArra) {
                InstituteModel *model = [InstituteModel modelWithDictionary:dic];
                [self.bottomDataArray addObject:model];

            }
            dispatch_async(dispatch_get_main_queue(), ^{
                NSMutableArray *indexsArra = [[NSMutableArray alloc] init];
                for (NSInteger i = 0; i < self.bottomDataArray.count; i++) {
                    NSIndexPath *index = [NSIndexPath indexPathForRow:i inSection:1];
                    [indexsArra addObject:index];
                }
                NSLog(@"下标位置%@",indexsArra);
                [UIView performWithoutAnimation:^{
                  [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:1]];
                    self.headerView.keepActiveIndex = self.selectedIndexpath;
                    [self.headerView.collectionView reloadData];
                }];
            });
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];

    });
}
/**
 开始获取机构所有类型列表
 */
-(void)getMiddleAndBottomListDataWithTypeId{
    dispatch_queue_t gloabQue = dispatch_get_global_queue(0, 0);
    dispatch_async(gloabQue, ^{
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        NSString *url = ServerIp@"/institutionApp/institutionList";
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:@"0",@"sortord",@"50",@"showCount", nil];
//        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:typeId,@"institutionCategory_id", nil];
        [manager POST:url parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSArray *listArra = jsonDic[@"list"];
            for (NSDictionary *dic in listArra) {
                InstituteModel *model = [InstituteModel modelWithDictionary:dic];
                [self.bottomDataArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.collectionView reloadData];
                //                [self.collectionView reloadData];
                //                NSIndexSet *index = [[NSIndexSet alloc] initWithIndex:1];
                //                [self.collectionView reloadSections:index];
                //                self.collectionView reloadItemsAtIndexPaths:<#(nonnull NSArray<NSIndexPath *> *)#>
            });
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
    });
}

/**
 选择机构去机构详情页面

 @param btn <#btn description#>
 */
-(void)GoInstitutionIntroduceAndDetail:(UIButton *)btn{
    InstituteModel *model;
    if (_isSearch) {
        model = self.resultsArray[btn.tag - 1000];
    }else{
        model = self.bottomDataArray[btn.tag - 1000];
    }
    InstitutionsDetailContainViewController *vc = [[InstitutionsDetailContainViewController alloc] init];
    vc.instituId = model.Id;
    vc.nameStr = model.name;
    vc.addressStr = [NSString stringWithFormat:@"%@%@%@%@",model.province,model.city,model.area,model.addresss];
    [self.navigationController pushViewController:vc animated:YES];
}


/**
 创建悬浮框
 */
-(void)createSuspensionBtn{
    GBPopMenuButtonView *view = [[GBPopMenuButtonView alloc] initWithItems:@[@"机构上传",@"置顶"] size:CGSizeMake(50, 50) type:GBMenuButtonTypeLineLeft isMove:NO];
    view.delegate = self;
//    view.isMove = NO;
    view.frame = CGRectMake(self.view.frame.size.width - scaleLeftAndRight(12) - 50, self.view.frame.size.height - scaleTopAndBottom(54) - 50, 50, 50);
    [self.view addSubview:view];
//    [view mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.equalTo(self.view.mas_right).offset(scaleLeftAndRight(-12));
//        make.bottom.equalTo(self.view.mas_bottom).offset(scaleTopAndBottom(54));
//        make.size.mas_equalTo(CGSizeMake(50, 50));
//   H }];
}
-(void)menuButtonSelectedAtIdex:(NSInteger)index{
    if (index == 0) {
        NSString *sessionID = [[NSUserDefaults standardUserDefaults] objectForKey:@"sessionId"];
        if (!sessionID) {
            LoginUserViewController *loginUserVc = [[LoginUserViewController alloc] init];
            loginUserVc.chooseTypeId = @"2";
            [self.navigationController pushViewController:loginUserVc animated:YES];
            return;
        }
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"Identity"] integerValue] == 2) {
            OrganationApplayINViewController *orgaIn = [[OrganationApplayINViewController alloc] init];
            [self.navigationController pushViewController:orgaIn animated:YES];
        }else if([[[NSUserDefaults standardUserDefaults] objectForKey:@"Identity"] integerValue] == 1){
            UIAlertController *aletController = [UIAlertController alertControllerWithTitle:@"对不起,您是个人用户" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [aletController addAction:action];
            [self presentViewController:aletController animated:YES completion:^{
                
            }];
        }

    }
    if (index == 1) {
        [self.collectionView setContentOffset:CGPointMake(0,20) animated:YES];
        
        [self.collectionView scrollRectToVisible:CGRectMake(0,0, 1,1) animated:NO];
        
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
    }
    NSLog(@"%ld",(long)index);
}
-(void)createLocaltionBtn{
    self.localBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.localBtn.frame = CGRectMake(0, 0, scaleLeftAndRight(80), scaleTopAndBottom(30));
//    self.localBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.localBtn setImage:[UIImage imageNamed:@"centerPageadd"] forState:UIControlStateNormal];
//    self.localBtn.contentEdgeInsets = UIEdgeInsetsMake(0, scaleLeftAndRight(20), 0, scaleTopAndBottom(-20));
    NSString *currentCity = [[NSUserDefaults standardUserDefaults] objectForKey:@"currentLocaltion"];
    [self.localBtn setTitle:currentCity forState:UIControlStateNormal];
    [self.localBtn addTarget:self action:@selector(CityChooseAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc] initWithCustomView:self.localBtn];
    if (@available(iOS 11.0, *))
    {
        self.navigationItem.rightBarButtonItems = @[rightBar];
    }
    else
    {
        UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
        flexSpace.width = -20;
        self.navigationItem.rightBarButtonItems = @[flexSpace,rightBar];
    }
    

}

/**
 城市列表选择

 */
-(void)CityChooseAction:(UIButton *)btn{
    LocaltionChooseViewController * picker = [[LocaltionChooseViewController alloc] init];
    picker.hotCitys = @[@"上海",@"北京",@"广州",@"深圳",@"杭州",@"天津"];
    UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:picker];
    picker.selectedAction = ^(NSString * city,LHCityPickerController * picker){
        NSLog(@"选中城市:%@",city);
        [btn setTitle:city forState:UIControlStateNormal];
        [picker dismissViewControllerAnimated:YES completion:nil];
    };
    picker.cityTile = btn.titleLabel.text;
    nav.transitioningDelegate = self;
    nav.modalPresentationStyle = UIModalPresentationCustom;
    [self presentViewController:nav animated:YES completion:nil];
}

/**
 距离和筛选的展示

 */
-(void)showDistanceViewChoose:(UIButton *)btn{
    if (self.collectionView.contentOffset.y != 20) {
        [self.collectionView setContentOffset:CGPointMake(0,20) animated:YES];
        
        [self.collectionView scrollRectToVisible:CGRectMake(0,0, 0,0) animated:NO];
        
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
        self.collectionView.scrollEnabled = NO;
    }
    NSInteger tag = btn.tag;
    switch (tag) {
        case 100001:
        {
            if (btn.selected) {
            }
            btn.selected = YES;
            btn.imageView.transform = CGAffineTransformMakeRotation(M_PI);
            UIButton *bbtn = [self.view viewWithTag:100002];
            bbtn.selected = NO;
            [_backView removeFromSuperview];
            [_screeView removeFromSuperview];
            [_distanceView removeFromSuperview];
            _backView = [[UIView alloc] initWithFrame:CGRectMake(0, scaleTopAndBottom(240) + scaleTopAndBottom(40) + 2 + 64, WIDTH, HEIGHT - scaleTopAndBottom(240) + scaleTopAndBottom(40) + 2 + 64)];
            UITapGestureRecognizer *taps = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removedemoBackview:)];
            [_backView addGestureRecognizer:taps];
            _backView.tag = 1000001;
            _backView.backgroundColor = [UIColor blackColor];
            _backView.alpha = 0.5;
            [self.view addSubview:_backView];
            
            _distanceView = [[DistanceView alloc] initWithFrame:CGRectMake(0, scaleTopAndBottom(220) + scaleTopAndBottom(40) + 2 + 64, WIDTH,240)];
            __weak typeof(DistanceView *)weakDistanceView = _distanceView;
            __weak typeof(UIView*)weakBackView = _backView;
            __weak typeof (self) weakSelf = self;
            _distanceView.sendBlock = ^(NSString *valueStr) {
                NSLog(@"%@",valueStr);
                [weakSelf.bottomDataArray removeAllObjects];
                [weakBackView removeFromSuperview];
                [weakDistanceView removeFromSuperview];
                weakSelf.collectionView.scrollEnabled = YES;
                [weakSelf.collectionView setContentOffset:CGPointMake(0,20) animated:YES];
                
                [weakSelf.collectionView scrollRectToVisible:CGRectMake(0,0, 1,1) animated:NO];
                
                [weakSelf.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
                btn.imageView.transform = CGAffineTransformMakeRotation(M_PI);
                btn.selected = NO;
                NSString *instiId = [[NSUserDefaults standardUserDefaults] objectForKey:@"insitiId"];
                [[NSUserDefaults standardUserDefaults] setObject:valueStr forKey:@"sortFunc"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                [weakSelf getMiddleAndBottomListDataWithTypeId:instiId AndWithSort:valueStr];
            };
            [self.view addSubview:_distanceView];
            [self.view bringSubviewToFront:_distanceView];

        }
            break;
          case 100002:
        {
            btn.selected = YES;
            UIButton *bbtn = [self.view viewWithTag:100001];
                        bbtn.imageView.transform = CGAffineTransformMakeRotation(M_PI);
            bbtn.selected = NO;
            [_backView removeFromSuperview];
            [_screeView removeFromSuperview];
            [_distanceView removeFromSuperview];
            _backView = [[UIView alloc] initWithFrame:CGRectMake(0, scaleTopAndBottom(240) + scaleTopAndBottom(40) + 2 + 64, WIDTH, HEIGHT - scaleTopAndBottom(240) + scaleTopAndBottom(40) + 2 + 64)];
            _backView.tag = 1000002;
            UITapGestureRecognizer *taps = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removedemoBackview:)];
            [_backView addGestureRecognizer:taps];
            _backView.backgroundColor = [UIColor blackColor];
            _backView.alpha = 0.5;
            [self.view addSubview:_backView];
            _screeView = [[InstituTypeChooseView alloc] initWithFrame:CGRectMake(0, scaleTopAndBottom(220) + scaleTopAndBottom(40) + 2 + 64, WIDTH,scaleTopAndBottom(220))];
            __weak typeof(InstituTypeChooseView *) weakscreeView = _screeView;
            __weak typeof(UIView*)weakBackView = _backView;
            __weak typeof (self) weakSelf = self;
            _screeView.closeViewBlock = ^{
                [weakBackView removeFromSuperview];
                [weakscreeView removeFromSuperview];
                weakSelf.collectionView.scrollEnabled = YES;
                [weakSelf.collectionView setContentOffset:CGPointMake(0,20) animated:YES];
                
                [weakSelf.collectionView scrollRectToVisible:CGRectMake(0,0, 1,1) animated:NO];
                
                [weakSelf.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
                btn.selected = NO;
                __strong typeof(self) strongself = weakSelf;
                
                [strongself.backView removeFromSuperview];
                NSLog(@"璇去到的%@",strongself.screeView.chooseDataArray);
                NSArray *array = [strongself backNewArray:strongself.screeView.chooseDataArray];
                NSLog(@"传递过来的所有key%@",array);
                NSLog(@"你要的键值对%@",strongself.screeView.vlauesAndIdsArray);
                for (NSInteger i = 0; i < strongself.screeView.vlauesAndIdsArray.count; i++) {
                    NSDictionary *dict = strongself.screeView.vlauesAndIdsArray[i];
                    NSLog(@"小字典%@",dict);
//                    NSLog(@"选去过啦%@",strongself.chooseShowArray);
                    NSLog(@"哈哈哈哈%@",[dict allValues][0]);
                    for (NSInteger j = 0; j < strongself.screeView.chooseDataArray.count; j++) {
                        NSDictionary *vlaueDic = strongself.screeView.chooseDataArray[j];
                        NSString *valueee = [vlaueDic allValues][0];
                        if ([valueee isEqual:[dict allValues][0]]) {
                            [strongself.chooseIdsArray addObject:[dict allKeys][0]];
                        }
                    }
                }
                NSLog(@"%@",strongself.chooseIdsArray);
            };
            
            [self.view addSubview:_screeView];
            [self.view bringSubviewToFront:_screeView];
        }
        default:
            break;
    }
    
    
}

/**
 移除筛选功能

 */
-(void)removedemoBackview:(UITapGestureRecognizer *)tap{
    UIView *view = tap.view;
    if (view.tag == 1000001) {
        [_distanceView removeFromSuperview];
        self.leftbtn.selected = NO;
        self.leftbtn.imageView.transform = CGAffineTransformMakeRotation(M_PI);
    }
    if (view.tag == 1000002) {
        [_screeView removeFromSuperview];
        self.rightbtn.selected = NO;
    }
    [view removeFromSuperview];
    self.collectionView.scrollEnabled = YES;
    [self.collectionView setContentOffset:CGPointMake(0,20) animated:YES];
    [self.collectionView scrollRectToVisible:CGRectMake(0,0, 1,1) animated:NO];
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
}
-(void)showShaixuanViewChoose:(UITapGestureRecognizer *)tap{
    [_backView removeFromSuperview];
    [_distanceView removeFromSuperview];
    self.collectionView.scrollEnabled = YES;
    [self.collectionView setContentOffset:CGPointMake(0,20) animated:YES];
    [self.collectionView scrollRectToVisible:CGRectMake(0,0, 1,1) animated:NO];
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
    [self.collectionView setContentOffset:CGPointMake(0,20) animated:YES];
    [self.collectionView scrollRectToVisible:CGRectMake(0,0, 1,1) animated:NO];
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
    self.collectionView.scrollEnabled = NO;
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, scaleTopAndBottom(240) + scaleTopAndBottom(40) + 2 + 64, WIDTH, HEIGHT - scaleTopAndBottom(240) + scaleTopAndBottom(40) + 2 + 64)];
    
    backView.backgroundColor = [UIColor blackColor];
    backView.alpha = 0.5;
    [self.view addSubview:backView];
    
    _screeView = [[InstituTypeChooseView alloc] initWithFrame:CGRectMake(0, scaleTopAndBottom(240) + scaleTopAndBottom(40) + 2 + 64, WIDTH,230)];
    [self.view addSubview:_screeView];
    [self.view bringSubviewToFront:_screeView];
}

#pragma mark: 设置顶部导航搜索部分
- (void)initSearchBar
{
    self.navigationItem.titleView = self.searchBar;
    if (@available(iOS 11.0, *))
    {
        [self.searchBar.heightAnchor constraintLessThanOrEqualToConstant:44].active = YES;
    }
    else
    {
        
    }
    
    
}

#pragma mark: getter method EVNCustomSearchBar
- (EVNCustomSearchBar *)searchBar
{
    if (!_searchBar)
    {
        _searchBar = [[EVNCustomSearchBar alloc] initWithFrame:CGRectMake(0, 20, WIDTH, 44)];
        
        _searchBar.backgroundColor = [UIColor clearColor]; // 清空searchBar的背景色
        _searchBar.iconImage = [UIImage imageNamed:@"sousuo"];
        _searchBar.iconAlign = EVNCustomSearchBarIconAlignCenter;
        _searchBar.isHiddenCancelButton = YES;
        [_searchBar setPlaceholder:@"全国儿童机构搜索"];  // 搜索框的占位符
        _searchBar.delegate = self; // 设置代理
        [_searchBar sizeToFit];
    }
    return _searchBar;
}

#pragma mark: EVNCustomSearchBar delegate method
- (BOOL)searchBarShouldBeginEditing:(EVNCustomSearchBar *)searchBar
{
    SearchResultViewController *resultVc = [[SearchResultViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:resultVc];
    nav.transitioningDelegate = self;
    nav.modalPresentationStyle = UIModalPresentationCustom;
    [self presentViewController:nav animated:YES
                     completion:^{
                          [self.searchBar resignFirstResponder];
                     }];
    NSLog(@"class: %@ function:%s", NSStringFromClass([self class]), __func__);
    return YES;
}
-(void)viewWillDisappear:(BOOL)animated{
    [self.searchBar resignFirstResponder];
}
//- (void)searchBarTextDidBeginEditing:(EVNCustomSearchBar *)searchBar
//{
//    SearchResultViewController *resultVc = [[SearchResultViewController alloc] init];
//    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:resultVc];
//    nav.transitioningDelegate = self;
//    nav.modalPresentationStyle = UIModalPresentationCustom;
//    [self presentViewController:nav animated:YES
//                 completion:^{
//
//    }];
//    NSLog(@"这个是不跳转的吗");
//    NSLog(@"class: %@ function:%s", NSStringFromClass([self class]), __func__);
//}

//- (BOOL)searchBarShouldEndEditing:(EVNCustomSearchBar *)searchBar
//{
//
//    NSLog(@"class: %@ function:%s", NSStringFromClass([self class]), __func__);
//    return YES;
//}
//
//- (void)searchBarTextDidEndEditing:(EVNCustomSearchBar *)searchBar
//{
//
//    NSLog(@"这个是不跳转的吗");
//    NSLog(@"class: %@ function:%s", NSStringFromClass([self class]), __func__);
//}
//
//- (void)searchBar:(EVNCustomSearchBar *)searchBar textDidChange:(NSString *)searchText
//{
//
//
//    NSLog(@"class: %@ function:%s", NSStringFromClass([self class]), __func__);
//}
//
//- (BOOL)searchBar:(EVNCustomSearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
//{
//    NSLog(@"class: %@ function:%s", NSStringFromClass([self class]), __func__);
//    return YES;
//}
//
//- (void)searchBarSearchButtonClicked:(EVNCustomSearchBar *)searchBar
//{
//    _isSearch = YES;
//    [self.resultsArray removeAllObjects];
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    NSString *url = ServerIp@"/institutionApp/institutionList";
//    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:searchBar.text,@"institution_name", nil];
//     NSLog(@"参数的值%@",param);
//    [manager POST:url parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
//
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
//        NSLog(@"错误信息%@",jsonDic[@"msg"]);
//        NSLog(@"%@",jsonDic);
//        NSArray *listArra = jsonDic[@"list"];
//        if (listArra.count == 0) {
//            
//        }else{
//            for (NSDictionary *dic in listArra) {
//                InstituteModel *model = [InstituteModel modelWithDictionary:dic];
//                [self.resultsArray addObject:model];
//            }
//            [self.collectionView reloadData];
//        }
//
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"%@",error);
//    }];
//    NSLog(@"class: %@ function:%s", NSStringFromClass([self class]), __func__);
//}
//
//- (void)searchBarCancelButtonClicked:(EVNCustomSearchBar *)searchBar
//{
//    _isSearch = NO;
//    [self.collectionView reloadData];
//    NSLog(@"class: %@ function:%s", NSStringFromClass([self class]), __func__);
//}
//
//- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
//{
//    [self.searchBar resignFirstResponder];
//}f
//
//-(NSMutableArray *)resultsArray{
//    if (_resultsArray == nil) {
//        _resultsArray = [[NSMutableArray alloc] init];
//    }
//    return _resultsArray;
//}

-(NSArray *)backNewArray:(NSMutableArray *)arra{
    NSMutableArray *keysArra = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < arra.count; i++) {
        NSDictionary *dic = arra[i];
        [keysArra addObject:[dic allKeys][0]];
    }
    NSSet *set = [NSSet setWithArray:keysArra];
    return   [set allObjects];
}
-(NSMutableArray *)bckeAllChooseDateWithNewArray:(NSArray *)arr{
    NSMutableArray *backArray = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < arr.count; i++) {
        NSString *key = arr[i];
        NSMutableDictionary *dictt = [[NSMutableDictionary alloc] init];
        NSMutableArray *arra = [[NSMutableArray alloc] init];
        for (NSInteger j = 0; j < self.screeView.chooseDataArray.count; j++) {
            NSDictionary *dic = self.screeView.chooseDataArray[j];
            NSLog(@"哲哲字典%@",dic);
            if ([[dic allKeys][0] isEqual:key]) {
                [arra addObject:[dic allValues][0]];
            }

        }
        NSLog(@"这哲哲%@",arra);
        [dictt setObject:arra forKey:key];
        [backArray addObject:dictt];
    }
    return backArray;
}
-(NSMutableArray *)chooseIdsArray{
    if (_chooseIdsArray == nil) {
        _chooseIdsArray = [[NSMutableArray alloc] init];
    }
    return _chooseIdsArray;
}


//-(void)addRefresh{
//    self.collectionView.mj_footer = [MJRefreshBackFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
//}
//-(void)loadMoreData{
//    self.currentPage++;
//    NSString *instituId = [[NSUserDefaults standardUserDefaults] objectForKey:@"insitiId"];
//    NSString *sortFunc = [[NSUserDefaults standardUserDefaults] objectForKey:@"sortFunc"];
//    if (sortFunc) {
//           [self getMiddleAndBottomListDataWithTypeId:instituId AndWithSort:sortFunc];
//    }else{
//            [self getMiddleAndBottomListDataWithTypeId:instituId AndWithSort:@"0"];
//    }
//
//}
//-(void)sendAllDataValue:(UIButton *)btn{
//    NSLog(@"获取到的所有数据%@",_shareView.chooseDataArray);
//    [UIView animateWithDuration:0.1 animations:^{
//        [_backView removeFromSuperview];
//        [_shareView removeFromSuperview];
//    }];
//
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
